package com.skiving.cloud.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.skiving.cloud.admin.entity.SysTenant;
import com.skiving.cloud.common.utils.PageParameter;
import com.skiving.cloud.admin.entity.SysTenantMenu;
import com.skiving.cloud.admin.mapper.SysTenantMenuMapper;
import com.skiving.cloud.admin.service.SysTenantMenuService;
import com.skiving.cloud.common.utils.UuidUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.Utils;
import org.noear.solon.data.annotation.Transaction;

import java.util.Arrays;
import java.util.List;

/**
 * 租户资源菜单范围 服务层实现。
 *
 * @author skivingcloud
 * @since 2025-03-08
 */
@Component
public class SysTenantMenuServiceImpl extends ServiceImpl<SysTenantMenuMapper, SysTenantMenu>  implements SysTenantMenuService {
    /**
     * 分页查询租户资源菜单范围
     *
     * @param parameter 查询参数
     * @return 分页查询结果
     */
    @Override
    public Page<SysTenantMenu> queryByPage(PageParameter<SysTenantMenu> parameter){
        Page<SysTenantMenu> page = new Page<>(parameter.getPage(), parameter.getPageSize());
        QueryWrapper queryWrapper = QueryWrapper.create();
        if (parameter.getParam() != null) {
            //查询条件
            if (Utils.isNotBlank(parameter.getParam().getId())) {
                queryWrapper.and(SysTenantMenu::getId).like(parameter.getParam().getId());
            }
            if (Utils.isNotBlank(parameter.getParam().getTenantId())) {
                queryWrapper.and(SysTenantMenu::getTenantId).like(parameter.getParam().getTenantId());
            }
            if (Utils.isNotBlank(parameter.getParam().getMenuId())) {
                queryWrapper.and(SysTenantMenu::getMenuId).like(parameter.getParam().getMenuId());
            }
        }
        return this.page(page, queryWrapper);
    }

    /**
     * 根据租户id查询租户的菜单权限范围
     *
     * @param tenantId 租户id
     * @return 租户资源关系
     */
    @Override
    public List<SysTenantMenu> getResTreeByTenantId(String tenantId) {
        QueryWrapper queryWrapper = QueryWrapper.create().where(SysTenantMenu::getTenantId).eq(tenantId);
        return this.mapper.selectListByQuery(queryWrapper);
    }

    /**
     * 设置租户资源权限
     *
     * @param tenant 租户资源权限信息
     */
    @Override
    @Transaction
    public void setSysTenantMenu(SysTenant tenant) {
        String[] res = tenant.getResId();
        QueryWrapper queryWrapper = QueryWrapper.create().where(SysTenantMenu::getTenantId).eq(tenant.getId());
        this.mapper.deleteByQuery(queryWrapper);
        this.mapper.insertBatch(Arrays.stream(res).map(m -> {
            SysTenantMenu sysTenantMenu = new SysTenantMenu();
            sysTenantMenu.setId(UuidUtil.get32UUID());
            sysTenantMenu.setTenantId(tenant.getId());
            sysTenantMenu.setMenuId(m);
            return sysTenantMenu;
        }).toList());
    }
}
